package org.szy.plugin.dev.controller;

import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.DownloadedFile;
import org.noear.solon.core.handle.ModelAndView;
import org.noear.solon.core.handle.UploadedFile;
import org.noear.solon.validation.annotation.NotNull;
import org.noear.solon.validation.annotation.Valid;
import org.noear.solon.validation.annotation.Validated;
import org.szy.core.common.controller.BaseController;
import org.szy.core.common.entity.R;
import org.szy.core.common.uilts.FileUploadUtils;
import org.szy.plugin.dev.entity.DevFile;
import org.szy.plugin.dev.param.DevFileUploadParam;
import org.szy.plugin.dev.service.DevFileService;

import java.util.ArrayList;
import java.util.List;

/**
 * 文件控制器
 *
 * @author wangbuhao
 * @date 2023/02/23 16:23
 */
@Mapping("/dev/file")
@Controller
@Valid
public class DevFileController extends BaseController<DevFile> {

    private final String PATH_PREFIX = "dev/file/";
    @Inject
    private DevFileService devFileService;

    @Get
    @Mapping("/upload")
    public ModelAndView upload() {
        ModelAndView view = new ModelAndView(PATH_PREFIX + "upload");
        return view;
    }

    /**
     * 删除文件
     *
     * @author wangbuhao
     * @date 2023/02/23 16:23
     */
    @Delete
    @Mapping("/delete")
    public R<?> delete(@NotNull Long id) {
        boolean delete = devFileService.removeById(id);
        return R.bool(delete, "删除成功", "删除失败，数据可能正在使用或已删除");
    }

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 上传后的地址
     */
    @Post
    @Mapping("/upload")
    public R<?> upload(UploadedFile file, DevFileUploadParam devFileUploadParam) {
        DevFile devFile = devFileService.upload(file, devFileUploadParam);
        return R.data(devFile);
    }

    /**
     * 上传文件
     *
     * @param files 多个文件
     * @return 上传后的地址
     */
    @Post
    @Mapping("/uploads")
    public R<?> uploads(UploadedFile[] files, DevFileUploadParam devFileUploadParam) {
        try {
            List<DevFile> list = new ArrayList<>();
            for (UploadedFile file : files) {
                DevFile devFile = devFileService.upload(file, devFileUploadParam);
                list.add(devFile);
            }
            return R.ok("上传文件成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("上传文件失败，原因：" + e.getMessage());
        }
    }

    /**
     * 根据唯一标识获取下载地址
     */
    @Get
    @Mapping("/download")
    public DownloadedFile download(String id) {
        DevFile devFile = devFileService.getById(id, "name,original_name,network_path,storage_path");
        return FileUploadUtils.download(devFile.getStoragePath(), devFile.getOriginalName());
    }

}
